window.onload=function(){
	//循环显示列表
	showList();
	//显示总金额
	totalMoneyFn();
}
//原始列表数组
let arr=[
		{
			checked:true,
			name:"迪奥999色号口红",
			num:3,
			price:330,
			shijian:"2023-01-11 08:30:00"
		},
		{
			checked:false,
			name:"兰蔻196色号口红",
			num:1,
			price:320,
			shijian:"2023-01-11 08:30:00"
		}
	];
//显示列表
function showList(){
	let str="";
	for (let i=0;i<arr.length;i++) {
		str+=`<tr>
			<td>
				<div class="custom-control custom-switch" >
					<input type="checkbox" class="custom-control-input" onclick="switchTab(${i})" id="cb${i+1}" ${arr[i].checked?'checked':''}>
					<label class="custom-control-label" for="cb${i+1}"> ${arr[i].checked?'已选':'未选'}</label>
				</div>
			</td>
			<td>${i+1}</td>
			<td>${arr[i].name}</td>
			<td>${arr[i].num}</td>
			<td>￥${arr[i].price}</td>
			<td>￥${arr[i].num*arr[i].price}</td>
			<td>${arr[i].shijian}</td>
			<td>
				<a href="javascript:;" onclick="add(${i})">增加</a>
				<a href="javascript:;" onclick="minus(${i})">减少</a>
				<a href="javascript:;" onclick="deleteItem(${i})">删除</a>
			</td>
		</tr>`;	
	}
	let tbody=document.getElementById("tbody");
	tbody.innerHTML=str;
}
//增加
function add(idx){
	arr[idx].num++;
	showList();
	totalMoneyFn();
}
//减少
function minus(idx){
	if(arr[idx].num>0){
		arr[idx].num--;
	}else{
		arr[idx].num=0;
		// arr[idx].checked=false;
		alert("不能在减了o(╥﹏╥)o")
	}
	showList();
	totalMoneyFn();
}
//删除
function deleteItem(idx){
	arr.splice(idx,1);
	showList();
	totalMoneyFn();
}
//总金额
function totalMoneyFn(){
	let total=arr.reduce((prev,item)=>{
		if(item.checked){
			prev+=item.num*item.price
		}
		return prev;
	},0)
	document.getElementById("totalMoney").innerHTML=total.toFixed(2);
}
//切换是否选中
function switchTab(idx){
	console.log(this.innerHTML);
	arr[idx].checked=!arr[idx].checked;
	let flag=arr.some(item=>{
		if(!item.checked){
			return true; 
		}
	})
	if(flag){
		document.getElementById("cb0").checked=false;
	}else{
		document.getElementById("cb0").checked=true;
	}
	totalMoneyFn();
}
//添加项目
function addItem(){
	let brandName=document.getElementById("brandName").value;
	let addNum=document.getElementById("addNum").value;
	let addPrice=document.getElementById("addPrice").value;
	arr.push({
		checked:true,
		name:brandName,
		num:addNum,
		price:addPrice,
		shijian:nowTime()
	})
	showList();
    totalMoneyFn();
}
//当前时间
function nowTime(){
	let date=new Date();
	let year=date.getFullYear();
	let month=date.getMonth()+1;
	let day=date.getDate();
	let h=date.getHours();
	let m=date.getMinutes();
	let s=date.getSeconds();
	let datetime=year+"-"+buqi(month)+"-"+buqi(day)+" "+buqi(h)+":"+buqi(m)+":"+buqi(s);
	return datetime;
}
//补齐两位
function buqi(num){
	return num<10?"0"+num:num;
}
//全选 全部选
function checkAll(e){
	arr.forEach(item=>{
		item.checked=e.checked;
	})
	showList();
	totalMoneyFn();
}